package com.lizhenyao.waimai.controller;

import com.google.common.collect.Lists;
import com.lizhenyao.waimai.dataobject.ProductCategory;
import com.lizhenyao.waimai.dataobject.ProductInfo;
import com.lizhenyao.waimai.service.ICategoryService;
import com.lizhenyao.waimai.service.IProductService;
import com.lizhenyao.waimai.utils.ResultVoUtil;
import com.lizhenyao.waimai.vo.ProductInfoVO;
import com.lizhenyao.waimai.vo.ProductVO;
import com.lizhenyao.waimai.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lizhenyao
 * @Desciption:
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private IProductService iProductService;

    @Autowired
    private ICategoryService iCategoryService;

    @GetMapping("/list")
    public ResultVO list(){
        // 1.查询所有的商品
        List<ProductInfo> productInfoList = iProductService.findUpAll();
        // 2.查询类目(一次性查询)
        //  使用java8的Lambda表达式
        List<Integer> categoryList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> productCategoryList = iCategoryService.findByCategoryTypeIn(categoryList);

        // 3.拼装数据
        List<ProductVO> productVOList = Lists.newArrayList();
        for (ProductCategory productCategory : productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVO> productInfoVOList = Lists.newArrayList();
            for (ProductInfo productInfo : productInfoList) {
                if (productInfo.getCategoryType().equals(productVO.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVoUtil.success(productVOList);
    }
}
